package com.uestc.simchat;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

public class SCLoginActivity extends AppCompatActivity {

    private EditText userNameView;
    private EditText passwordView;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (EMClient.getInstance().isLoggedIn()) {
            startActivity(new Intent(SCLoginActivity.this, MainActivity.class));
            finish();
        }

        setContentView(R.layout.activity_login);

        userNameView = (EditText) findViewById(R.id.sc_edit_username);
        passwordView = (EditText) findViewById(R.id.sc_edit_password);

        findViewById(R.id.sc_btn_signup).setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                signup();
            }
        });
        findViewById(R.id.sc_btn_signin).setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                signin();
            }
        });


    }
    /*注册*/
    private void signup(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(userNameView.getText().toString().trim(), passwordView.getText().toString().trim());
                    Log.e("SC", "注册成功");
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    Log.e("SC", "注册失败 " + e.getErrorCode() + ", " + e.getMessage());
                }
            }
        }).start();
    }
    /*登录*/
    private void signin(){
        EMClient.getInstance().login(userNameView.getText().toString().trim(), passwordView.getText().toString().trim(), new EMCallBack() {
            @Override
            public void onSuccess() {
                startActivity(new Intent(SCLoginActivity.this, MainActivity.class));
                finish();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("SC", "登录失败 " + i + ", " + s);
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }
}
